from django.db import models
from pets.models import Pet
import numpy as np
import joblib
from django.conf import settings
import os


class HealthAnalysis(models.Model):
    pet = models.OneToOneField(Pet, on_delete=models.CASCADE, related_name='health_analysis')
    last_analysis_date = models.DateField(auto_now=True)
    health_score = models.FloatField(default=0.0)
    predicted_health_issues = models.JSONField(default=dict)
    recommendations = models.TextField(blank=True)

    def analyze_health(self):
        # 加载预训练的机器学习模型
        model_path = os.path.join(settings.BASE_DIR, 'ml_models', 'pet_health_predictor.pkl')
        model = joblib.load(model_path)

        # 获取宠物健康记录数据
        records = self.pet.health_records.order_by('-date')[:10]
        if not records:
            return

        # 准备特征数据
        features = np.array([
            [r.weight, r.height, r.temperature] for r in records
        ]).flatten()

        # 如果记录不足10条，填充平均值
        if len(records) < 10:
            avg_weight = np.mean([r.weight for r in records])
            avg_height = np.mean([r.height for r in records]) if any(r.height for r in records) else 0
            avg_temp = np.mean([r.temperature for r in records]) if any(r.temperature for r in records) else 0
            features = np.pad(features, (0, 30 - len(features)), 'constant', constant_values=(
                avg_weight, avg_height, avg_temp
            ))

        # 进行预测
        prediction = model.predict([features])
        self.health_score = prediction[0][0] * 100
        self.predicted_health_issues = {
            'obesity_risk': prediction[0][1] * 100,
            'dental_issues': prediction[0][2] * 100,
            'joint_problems': prediction[0][3] * 100
        }

        # 生成建议
        recommendations = []
        if prediction[0][1] > 0.7:
            recommendations.append("High obesity risk detected. Consider adjusting diet and increasing exercise.")
        if prediction[0][2] > 0.6:
            recommendations.append("Potential dental issues. Schedule a dental checkup.")
        if prediction[0][3] > 0.5:
            recommendations.append("Joint problems possible. Consider supplements or vet consultation.")

        self.recommendations = "\n".join(recommendations)
        self.save()